<template>
  <div>

    <template v-if="itemdata.sUITypeExp == 'normal'">

      <template>
        <input type="hidden" :id="index + '_' + itemdata.sField" v-model="itemdata.valuehidden" />
        <van-field :readonly="itemdata.sEditable==='false'"   size="large" placeholder="请选择" :id="index + '_' + itemdata.sField + '_ref'" clearable
          v-model="itemdata.value" :label="itemdata.sTitle" right-icon="search" @input="clearRefValue(itemdata)"
          @clear="clearRefValue(itemdata)" @change="openRef(itemdata, 'bodydata', indexName, index)"
          @click="openRef(itemdata, 'bodydata', indexName, index)"
          @click-right-icon="openRef(itemdata, 'bodydata', indexName, index)" :error-message="itemdata.errormsg" />
      </template>
      <!-- <template v-else>
      <van-cell  :title="itemdata.sTitle">
        <template #default>
          <div v-html="itemdata.value"></div>
        </template>
      </van-cell>
    </template> -->
    </template>
    <template v-else-if="itemdata.sUITypeExp == 'multi'">
      <template>
        <input type="hidden" :id="index + '_' + itemdata.sField" v-model="itemdata.valuehidden" />
        <van-field :readonly="itemdata.sEditable==='false'"  size="large" placeholder="请选择" :id="index + '_' + itemdata.sField + '_ref'" clearable
          v-model="itemdata.value" :label="itemdata.sTitle" right-icon="search" @input="clearRefValue(itemdata)"
          @clear="clearRefValue(itemdata)" @click="openRefMulti(itemdata, 'bodydata', indexName, index)"
          @click-right-icon="openRefMulti(itemdata, 'bodydata', indexName, index)" :error-message="itemdata.errormsg" />
      </template>
      <!-- <template v-else>
      <van-cell  :title="itemdata.sTitle">
        <template #default>
          <div v-html="itemdata.value"></div>
        </template>
      </van-cell>
    </template> -->
    </template>
  </div>
</template>
<script>
import { Toast } from 'vant'
import Vue from 'vue'
import { base64encode } from '@/assets/js/tool.js'
Vue.use(Toast)
export default {
  data: function () {
    return {
      // clickmodel: {},
      // clickfrom: '',
      // clickindexName: '',
      // clickindex: 0
    }
  },
  // props: ['clickmodel', 'clickfrom', 'clickindexName', 'clickindex', 'jsondata', 'indexName', 'itemdata', 'ishead', 'index', 'activeNames'],
  props: {
    clickmodel: {
      type: Object,
      required: false
    },
    clickfrom: {
      type: String,
      required: false
    },
    clickindexName: {
      type: String,
      required: false
    },
    clickindex: {
      type: Number,
      required: false
    },
    jsondata: {
      type: Object,
      required: false
    },
    indexName: {
      type: String,
      required: false
    },
    itemdata: {
      type: Object,
      required: false
    },
    ishead: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      required: false
    },
    jsondataindex: {
      type: Number,
      required: false
    },
    jsondatai: {
      type: Number,
      required: false
    }
  },
  watch: {
    'itemdata.value': {
      handler(newval) {
        this.$emit('handleFiledLink', { sField: this.itemdata.sField, value: newval, ishead: this.ishead, index: this.index })
      }
    }
  },
  methods: {
    clearRefValue(datamodel) {
      // if (!datamodel.value) {
      //   return; // 如果输入框的值为空，不做任何操作
      // }
      // datamodel.value = ''; // 清空输入框的值
      if (datamodel.value === '') {
        datamodel.valuehidden = ''
      }
    },
    openRef(datamodel, datafrom, indexName, index) {
      if (datamodel.sEditable === 'false') {
        return
      }
      //console.log(datamodel.valuehidden + 'hidden')
      //console.log('datamodel', datamodel)
      //console.log('datafrom', datafrom)
      //console.log('indexName', indexName)
      //console.log('index', index)
      this.$emit('update:clickmodel', datamodel)
      this.$emit('update:clickfrom', datafrom)
      this.$emit('update:clickindexName', indexName)
      this.$emit('update:clickindex', index)
      if (this.jsondatai) {
        this.$emit('update:jsondataindex', this.jsondatai)
      }
      this.conditionValHidden = ''
      let inview = datamodel.inview
      if (inview) {
        let arrinview = inview.split(';')
        for (let inviewindex in arrinview) {
          let arrinviewdata = arrinview[inviewindex]
          let inviewdatas = arrinviewdata.split(':')
          if (inviewdatas[1] === 'eq') {
            if (datafrom === 'headdata') {
              for (let groupindex in this.jsondata.head) {
                for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
                  let item = this.jsondata.head[groupindex].groupvalue[itemindex]
                  if (item.sField === inviewdatas[2].split('_')[2]) {
                    this.conditionValHidden += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
                  }
                }
              }
            } else if (datafrom === 'bodydata') {
              for (let itemindex in this.jsondata.bodydata[indexName][index]) {
                let item = this.jsondata.bodydata[indexName][index][itemindex]
                if (item.sField === inviewdatas[0]) {
                  this.conditionValHidden += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
                }
              }
            }
          } else if (inviewdatas[1] === 'in') {
            //console.log('-------------' + datamodel.value)
            this.conditionValHidden += inviewdatas[0] + ':in:' + datamodel.value + ';'
          }
        }
      }
      let refparams = ''
      if (datamodel.idObject === 'fee' && datamodel.jsfunc === 'getFeebillFyzl()') { //  // 费用报销单表体费用类别
        let fyzl = ''
        for (let groupindex in this.jsondata.head) {
          for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
            let item = this.jsondata.head[groupindex].groupvalue[itemindex]
            if (item.sField === 'fyzl') {
              fyzl = item.valuehidden
            }
          }
        }
        if (!fyzl) {
          Toast('请先选择表头的费用种类')
          return
        }
        let json = {
          'feebill_fyzl': fyzl
        }
        //console.log(JSON.stringify(json))
        refparams = base64encode(JSON.stringify(json))
      }
      if (datamodel.idObject === 'dlprice' && datamodel.jsfunc === 'chenxinHzxdlProduct()') { // 辰欣项目代码
        refparams = []
        let iddep = ''
        let dlkh = ''
        for (let groupindex in this.jsondata.head) {
          for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
            let item = this.jsondata.head[groupindex].groupvalue[itemindex]
            if (item.sField === 'iddep') {
              iddep = item.valuehidden
              //console.log('inside...iddep' + iddep)
            }
            if (item.sField == 'dlkh') {
              dlkh = item.valuehidden
              //console.log('inside...dlkh' + iddep)
            }
          }
        }
        if (!dlkh) {
          Toast('请先选择联系人')
          return
        }
        if (!iddep) {
          Toast('请先选择部门')
          return
        }
        refparams = iddep + ';' + dlkh
      }
      // 每个逻辑需要单独写
      if (datamodel.idObject === 'sorders' && datamodel.jsfunc === 'getAccountForSorder()') {
        let agent = ''
        let consumer = ''
        let type = ''
        for (let groupindex in this.jsondata.head) {
          for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
            let item = this.jsondata.head[groupindex].groupvalue[itemindex]
            if (item.sField === 'agent') {
              agent = item.valuehidden
            } else if (item.sField === 'consumer') {
              consumer = item.valuehidden
            } else if (item.sField === 'type') {
              type = item.valuehidden
            }
          }
        }
        if (consumer === '') {
          Toast('请先选择客户')
          return
        }
        if (type === '297ef43353a100de0153a1fdcaa60611') {
          if (agent !== '') {
            Toast('自营模式不能输入代理商')
            return
          }
        } else {
          if (agent === '') {
            Toast('请先选择代理商')
            return
          }
        }
      }

      // 迈科维，销售订单明细，海外销售订单  产品插入点 (参照PC端逻辑)
      if (/^sorders\d?$/.test(datamodel.idObject) && datamodel.jsfunc === 'getAccountForSorderMkw()') {
        let consumer = ''
        let sheng = ''
        let date = ''
        let country = ''

        const fieldMap = {
          consumer: (value) => consumer = value,
          date: (value) => date = value,
          sheng: (value) => sheng = value,
          country: (value) => country = value
        }

        //console.log('this.jsondata.head', this.jsondata.head)
        this.jsondata.head.forEach(group => {
          group.groupvalue.forEach(item => {
            const handler = fieldMap[item.sField]
            if (handler) {
              handler(item.valuehidden || item.value)
            }
          })
        })

        sheng = sheng.length ? sheng : ''

        if (!date) {
          Toast('单据日期不能为空')
          return
        }

        if (consumer) {
          refparams = `${consumer};${date};${sheng};${country}`
        } else {
          Toast('请先输入客户')
          return
        }
      }
      // 迈科维，销售订单 经销商插入点 (参照PC端逻辑)
      if (/^sorder\d?$/.test(datamodel.idObject) && ['getDzForSorder()', 'getDzForSorder3()'].includes(datamodel.jsfunc)) {
        let date = ''
        let paycompany = ''
        let tgxydh = ''
        let psxydh = ''

        const fieldMap = {
          date: (value) => date = value,
          paycompany: (value) => paycompany = value,
          tgxydh: (value) => tgxydh = value,
          psxydh: (value) => psxydh = value
        }
        //console.log('this.jsondata', this.jsondata)
        this.jsondata.head.forEach(group => {
          group.groupvalue.forEach(item => {
            const handler = fieldMap[item.sField]
            if (handler) {
              handler(item.valuehidden || item.value)
            }
          })
        })

        if (!date) {
          Toast('单据日期不能为空')
          return
        }
        if (!paycompany) {
          Toast('发货主体不能为空!')
          return
        }
        //console.log('indexName:', indexName)
        //console.log('index:', index)
        // this.jsondata.bodydata['销售订单明细'][index].forEach(item => {
        //   const handler = fieldMap[item.sField]
        //   if (handler) {
        //     handler(item.valuehidden || item.value)
        //   }
        // });

        refparams = `${date};`
        if (tgxydh) {
          refparams += `tgxy;${tgxydh};`
        }
        if (psxydh) {
          refparams += `psxy;${psxydh}; `
        }
        refparams += `${paycompany}`
      }

      //console.log('xhjh: begin...')

      if (datamodel.idObject === 'xhjhdetail' && datamodel.jsfunc === 'chenxinXhjhProduct()') { // 辰欣项目代码
        //console.log('xhjhdetail:' + JSON.stringify(datamodel))
        let iddep = ''
        for (let groupindex in this.jsondata.head) {
          for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
            let item = this.jsondata.head[groupindex].groupvalue[itemindex]
            if (item.sField === 'iddep') {
              // alert(item.valuehidden)
              iddep = item.valuehidden
            }
          }
        }
        if (!iddep) {
          Toast('请检查部门是否为空!')
          return
        }
        refparams = iddep
      }
      //console.log('clickmodel-ref1', this.clickmodel, '2', datamodel, '3', this.conditionValHidden, '4', refparams)
      //console.log('datamodel', datamodel)
      let componentName = 'ref'
      if ((datamodel.idJoinObject === 'employee' || datamodel.idJoinObject === 'dep')) {
        componentName = 'orgRef'
      }
      this.$router.push({
        name: componentName,
        params: {
          stitle: this.itemdata.sTitle,
          bo: datamodel.idJoinObject,
          tobo: datamodel.idObject,
          field: datamodel.sField,
          fieldref: datamodel.sFieldRef,
          viewid: datamodel.sRefKey,
          conditionVal: '',
          conditionValHidden: '',
          classname: datamodel.classname,
          params: refparams,
          mode: 'single',
          datafrom: datafrom
        }
      })
    },
    openRefMulti(datamodel, datafrom, indexName, index) {
      if(datamodel.sEditable==='false'){
        return
      }
      this.$emit('update:clickmodel', datamodel)
      this.$emit('update:clickfrom', datafrom)
      this.$emit('update:clickindexName', indexName)
      this.$emit('update:clickindex', index)
      this.conditionValHidden = ''
      let inview = datamodel.inview
      if (inview !== '') {
        let arrinview = inview.split(';')
        for (let inviewindex in arrinview) {
          let arrinviewdata = arrinview[inviewindex]
          let inviewdatas = arrinviewdata.split(':')
          if (inviewdatas[1] === 'eq') {
            if (datafrom === 'headdata') {
              for (let groupindex in this.jsondata.head) {
                for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
                  let item = this.jsondata.head[groupindex].groupvalue[itemindex]
                  if (item.sField === inviewdatas[2].split('_')[2]) {
                    this.conditionValHidden += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
                  }
                }
              }
            } else if (datafrom === 'bodydata') {
              for (let itemindex in this.jsondata.bodydata[indexName][index]) {
                let item = this.jsondata.bodydata[indexName][index][itemindex]
                if (item.sField === inviewdatas[0]) {
                  this.conditionValHidden += inviewdatas[0] + ':eqref:' + item.valuehidden + ';'
                }
              }
            }
          } else if (inviewdatas[1] === 'in') {
            this.conditionValHidden += inviewdatas[0] + ':in:;'
          }
        }
      }
      // 每个逻辑需要单独写
      if (datamodel.idObject === 'sorders' && datamodel.jsfunc === 'getAccountForSorder()') {
        let agent = ''
        let consumer = ''
        let type = ''
        for (let groupindex in this.jsondata.head) {
          for (let itemindex in this.jsondata.head[groupindex].groupvalue) {
            let item = this.jsondata.head[groupindex].groupvalue[itemindex]
            if (item.sField === 'agent') {
              agent = item.valuehidden
            } else if (item.sField === 'consumer') {
              consumer = item.valuehidden
            } else if (item.sField === 'type') {
              type = item.valuehidden
            }
          }
        }
        if (consumer === '') {
          Toast('请先选择客户')
          return
        }
        if (type === '297ef43353a100de0153a1fdcaa60611') {
          if (agent !== '') {
            Toast('自营模式不能输入代理商')
            return
          }
        } else {
          if (agent === '') {
            Toast('请先选择代理商')
            return
          }
        }
      }
      let refname = 'refmulti'

      if (datamodel.idJoinObject == 'employee' || datamodel.idJoinObject === 'dep') {
        refname = 'orgRef'
      }
      this.$router.push({
        name: refname,
        params: {
          stitle: this.itemdata.sTitle,
          bo: datamodel.idJoinObject,
          tobo: datamodel.idObject,
          field: datamodel.sField,
          fieldref: datamodel.sFieldRef,
          viewid: datamodel.sRefKey,
          conditionVal: '',
          conditionValHidden: this.conditionValHidden,
          classname: datamodel.classname,
          valuehidden1: datamodel.valuehidden,
          datamodel1: datamodel,
          mode: 'multiple'
        }
      })
    }
  }
}
</script>
